package com.tansun.easycare.rule.rulemange.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tansun.easycare.rule.refemodel.entity.RuleReleModel;
import com.tansun.easycare.rule.refemodel.service.RuleReleModelService;
import org.kie.api.io.ResourceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.tansun.easycare.core.config.Global;
import com.tansun.easycare.modules.sys.utils.UserUtils;
import com.tansun.easycare.rule.codeblock.service.RuleCodeblockService;
import com.tansun.easycare.rule.common.ReferenceModel;
import com.tansun.easycare.rule.common.model.BaseModel;
import com.tansun.easycare.rule.common.service.RuleBaseService;
import com.tansun.easycare.rule.common.service.impl.RuleBaseServiceImpl;
import com.tansun.easycare.rule.datacomponent.service.IDataComponentService;
import com.tansun.easycare.rule.datacomponent.service.IDataMiningService;
import com.tansun.easycare.rule.datamodel.dao.RuleDataparamsDao;
import com.tansun.easycare.rule.datamodel.dao.RuleDatasetDao;
import com.tansun.easycare.rule.datamodel.entity.RuleDataparams;
import com.tansun.easycare.rule.datamodel.entity.RuleDataset;
import com.tansun.easycare.rule.decisiontree.service.DecisionTreeService;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.modelauthority.entity.RuleModelAuthority;
import com.tansun.easycare.rule.modelauthority.service.RuleModelAuthorityService;
import com.tansun.easycare.rule.referencedata.service.RuleReferenceDataService;
import com.tansun.easycare.rule.ruleflow.service.RuleFlowRectsService;
import com.tansun.easycare.rule.ruleflow.service.RuleFlowService;
import com.tansun.easycare.rule.rulegroup.service.RuleGroupService;
import com.tansun.easycare.rule.rulemange.dao.RuleManageDao;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.model.RuleManageVO;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.easycare.rule.ruleproj.service.RuleProjectRankService;
import com.tansun.easycare.rule.ruleversion.entity.RuleVersioninfo;
import com.tansun.easycare.rule.ruleversion.service.RuleVersioninfoService;
import com.tansun.easycare.rule.scoremodel.service.ScoreModelService;
import com.tansun.easycare.rule.table.decisiontable.service.DecisionTableService;
import com.tansun.easycare.rule.table.singletblindex.service.SingleTblIndexService;
import com.tansun.rule.common.KieBaseFactory;
import com.tansun.rule.common.ResourceContentInfo;
import com.tansun.rule.common.RuleModelTypeEnum;
import com.tansun.rule.utils.StringUtils;

@Service
public class RuleManageSerivceImpl extends RuleBaseServiceImpl<RuleManageDao, RuleManage> implements RuleManageService {

    @Autowired
    private RuleModelAuthorityService ruleModelAuthorityService;
    @Autowired
    private RuleVersioninfoService ruleVersioninfoService;
    @Autowired
    private RuleFlowRectsService ruleFlowRectsService;
    
    private RuleBaseService<?> ruleBaseService;
    
    @Autowired
    private RuleCodeblockService ruleCodeblockService;
	@Autowired
	private IDataMiningService dataMiningService;
    @Autowired
    private IDataComponentService dataComponentService;
    @Autowired
    private DecisionTreeService decisionTreeService;
    @Autowired
    private DecisionTableService decisionTableService;
    @Autowired
    private SingleTblIndexService singleTblIndexService;
    @Autowired
    private ScoreModelService scoreModelService;
    @Autowired
    private RuleFlowService ruleFlowService;
    @Autowired
    private RuleGroupService ruleGroupService;
    @Autowired
    private RuleDataparamsDao ruleDataparamsDao;
    @Autowired
    private RuleDatasetDao ruleDatasetDao;
    @Autowired
	private RuleProjectRankService ruleProjectRankService;
    @Autowired
    private RuleReferenceDataService ruleReferenceDataService;
    @Autowired
    private RuleReleModelService ruleReleModelService;

    
    public RuleManage saveOrUpdate(RuleManage ruleManage) throws BizException {
        boolean isNew = StringUtils.isEmpty(ruleManage.getId());
        if (ruleManage.getCreateDate() == null) {
        	ruleManage.setCreateDate(new Date());
        }
        //ruleManage.setUpdateDate(new Date());
        if (StringUtils.isEmpty(ruleManage.getId())) {
            ruleManage.setId(null);
            ruleManage.setIsNewRecord(false);
            ruleManage.setStatus("1");
            String type = RuleModelTypeEnum.getType(ruleManage.getModelType());
            if (StringUtils.isEmpty(ruleManage.getCode())) {
                ruleManage.setCode(this.generalCodeByType(type, ruleManage.getProjectCode()));
            }
            if (StringUtils.isEmpty(ruleManage.getVersion())) {
                ruleManage.setVersion("v1.00");
            } else {
//				ruleManage.initVersion();//COPY
            }
        } else {
//        	if(!RuleModelTypeEnum.DataMining.getCode().equals(ruleManage.getModelType())) {
    		RuleManage obj = this.get(ruleManage.getId());
            if (StringUtils.isEmpty(ruleManage.getName())) {
                ruleManage.setName(obj.getName());
            }
            ruleManage.setCode(obj.getCode());

    		String version = obj.getVersion();
    		if(version.contains("_modify")) {
    			ruleManage.setVersion(version.replace("_modify", ""));
    		}else {
    			ruleManage.setVersion(version);
                ruleManage.initVersion(ruleManage.getIsTemp());
    		}
        }
        if (ruleManage.getStatus() != null && !"2".equals(ruleManage.getStatus())){
	        if (isExists(ruleManage)) {
	        	ruleManage.setName(ruleManage.getName()+StringUtils.generateShortUuid());
	            //throw new BizException("E-000111");
	        }
        }
        this.save(ruleManage);
        if (isNew) {
            RuleModelAuthority ruleModelAuthority = new RuleModelAuthority();
            ruleModelAuthority.setManageId(ruleManage.getId());
            ruleModelAuthority.setProjectCode(ruleManage.getProjectCode());
            ruleModelAuthority.setOwner(UserUtils.getSysService().getUserById(ruleManage.getCreateBy()).getLoginName());
            ruleModelAuthority.setUsers(UserUtils.getSysService().getUserById(ruleManage.getUpdateBy()).getLoginName() + ";");
            this.ruleModelAuthorityService.save(ruleModelAuthority);
        }
        return ruleManage;
    }

    @Override
    public List<RuleManage> searchRuleTable(List<RuleManage> list, BaseModel param) {
        if (list == null) return list;
        List<RuleManage> result = new ArrayList<RuleManage>();
        for (RuleManage vo : list) {
            if (!StringUtils.isEmpty(param.getName()) && !vo.getName().contains(param.getName())) {
                continue;
            }
            if (!StringUtils.isEmpty(param.getStatus()) && !vo.getStatus().equals(param.getStatus())) {
                continue;
            }
            if (!StringUtils.isEmpty(param.getCreatedBy()) && !vo.getCreateBy().equals(param.getCreatedBy())) {
                continue;
            }
            if (!StringUtils.isEmpty(param.getCreatedOn()) && vo.getCreateDate().compareTo(new Date(param.getCreatedOn())) < 0) {
                continue;
            }
            if (!StringUtils.isEmpty(param.getModifiedOn()) && vo.getUpdateDate().compareTo(new Date(param.getModifiedOn())) > 0) {
                continue;
            }
            result.add(vo);
        }
        return result;
    }

    @Override
    public List<RuleManageVO> findRuleManageVO(Map<String, Object> map) {

        return this.dao.findRuleManageVO(map);
    }

    public List<RuleManageVO> findRuleManageVO(BaseModel condition) {
        return this.dao.findRuleManageByCondition(condition);
    }

    public RuleManage getById(String indexId) throws BizException {
        if (StringUtils.isEmpty(indexId))
            return null;
        RuleManage indexModel = this.get(indexId);
        return indexModel;
    }

    @Override
    public void updateAuthority(String id, String projectCode, String authTypeValue, String loginNames, String currLoginName) throws BizException {

        RuleManage ruleManage = new RuleManage();
        ruleManage.setId(id);
        ruleManage.setProjectCode(projectCode);
        List<RuleManage> list = this.dao.findList(ruleManage);
        if (list != null && list.size() > 0) {
            RuleManage updateManage = list.get(0);
            //updateManage.setUpdateBy(UserUtils.getUser().getId());
            updateManage.setUpdateDate(new Date());

            BaseModel baseModel = new BaseModel();
            baseModel.setVersion(updateManage.getVersion());
            baseModel.setStatus(updateManage.getStatus());

            RuleModelAuthority ruleModelAuthority = new RuleModelAuthority();
            ruleModelAuthority.setManageId(updateManage.getId());
            List<RuleModelAuthority> aList = this.ruleModelAuthorityService.findList(ruleModelAuthority);
            RuleModelAuthority updateAuthority = null;
            if (aList != null && aList.size() > 0) {
                updateAuthority = aList.get(0);
                baseModel.setUsers(updateAuthority.getUsers());
                baseModel.setOwner(updateAuthority.getOwner());
                this.setAuthInfo(authTypeValue, loginNames, currLoginName, baseModel);
                baseModel.InitModifiedContent(null);
                updateAuthority.setUsers(baseModel.getUsers());
                updateAuthority.setOwner(baseModel.getOwner());
                updateAuthority.setLocker(baseModel.getLocker());
                this.ruleModelAuthorityService.save(updateAuthority);
            }
            updateManage.setVersion(baseModel.getVersion());
            this.dao.update(updateManage);
        }

    }

    /**
     * 设置权限信息
     *
     * @param authTypeValue 权限类别
     * @param loginNames    被授权用户名串，“;”分开
     * @param currLoginName 当前用户名称
     * @param baseModel     索引对象
     */
    private void setAuthInfo(String authTypeValue, String loginNames, String currLoginName, BaseModel baseModel) {
        //指示持久化的逻辑不要更新版本，本身不持久化到xml文件中
        baseModel.setUpgrad(false);
        //转交
        if ("transf".equals(authTypeValue)) {
            String ownername = loginNames.replace(";", "").trim();

            baseModel.setOwner(ownername);
            if (baseModel.getUsers().indexOf(ownername) < 0) {
                baseModel.setUsers(baseModel.getUsers() + ownername + ";");
            }
            //授权
        } else if ("append".equals(authTypeValue)) {
            baseModel.setUsers(loginNames);
            //冻结
        } else if ("freeze".equals(authTypeValue)) {
            baseModel.setLocker(currLoginName);
            //解冻
        } else if ("unfreeze".equals(authTypeValue)) {
            baseModel.setLocker("");
        }
    }

    @Override
    public boolean isExists(RuleManage queryManage) throws BizException {
        String name = queryManage.getName();
        if (StringUtils.isEmpty(name))
            throw new BizException("E-000101");
        String status = queryManage.getStatus();
        String modelType = queryManage.getModelType();
        String manageId = queryManage.getId();
        String projectCode = queryManage.getProjectCode();
        if (status != null && !"0".equals(status)) {
            RuleManage ruleInfo = new RuleManage();
            ruleInfo.setModelType(modelType);
            ruleInfo.setName(name);
            ruleInfo.setProjectCode(projectCode);
            List<RuleManage> list = this.findList(ruleInfo);
            if (list != null) {
                for (RuleManage tmpManage : list) {
                    if ("0".equals(tmpManage.getStatus()))
                        continue;
                    if (StringUtils.isEmpty(manageId) && tmpManage.getName().equals(name)) {
                        return true;
                    } else {
                        if (!tmpManage.getId().equals(manageId) && tmpManage.getName().equals(name)) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    @Override
    public PageInfo<RuleManageVO> findRuleManageVO(Page<RuleManageVO> page, RuleManageVO ruleManage) {
        ruleProjectRankService.setRefRandIds(ruleManage,false);
        PageInfo<RuleManageVO> pageInfo = new PageInfo<>(this.dao.findRuleManageVO(ruleManage));
        return pageInfo;
    }

    /**
     * 设置规则发布服务委托
     */
    @Override
    public void setRuleBaseService(RuleBaseService<?> ruleBaseService) {
        this.ruleBaseService = ruleBaseService;
    }

    /**
     * 规则发布
     */
    public void publicRule(String manageId) throws BizException {
        publicRule(manageId, null);
    }

    /**
     * 规则版本回退
     */
    public void publicRule(String manageId, String version) throws BizException {
        RuleManage manage = this.getById(manageId);
        if (manage == null) {
            throw new BizException("E-100001");
        }
        if (!StringUtils.isEmpty(version)) {
            manage.setOldVersion(version);
            manage.setStatus("1");
        } else {
            manage.setOldVersion(manage.getVersion());
            manage.setStatus("2");
        }
        this.saveOrUpdate(manage);
        if (this.ruleBaseService != null) {
            this.ruleBaseService.updateVersion(manage);
        } else {
            this.updateVersion(manage);
        }
        //更新规则内容
        ruleVersioninfoService.updateRuleContent(manage);
    }

    @Override
    public void copyRule(String manageId,String rankRelationId) throws BizException {
        RuleManage manage = this.getById(manageId);
        if (manage == null)
            throw new BizException("E-100001");
        RuleManage newRule = new RuleManage(manage);
        newRule.setRankRelationId(rankRelationId);
        newRule = this.saveOrUpdate(newRule);
        if (this.ruleBaseService != null) {
            this.ruleBaseService.copyRule(manage, newRule);
        } else {
            throw new BizException("");
        }
        if ("19".equals(manage.getModelType())) {
        }else {

            RuleVersioninfo verCon = new RuleVersioninfo();
            verCon.setManageId(manage.getId());
            verCon.setVersion(manage.getVersion());
            List<RuleVersioninfo> verList = ruleVersioninfoService.findList(verCon);
            if (verList != null && verList.size() > 0) {
	            RuleVersioninfo verInfo = verList.get(0);
	            verInfo.setId(null);
	            verInfo.setManageId(newRule.getId());
	            verInfo.setVersion(newRule.getVersion());
	            try {
	                String ruleContent = verInfo.getRuleContent();
//	                ruleContent = ruleContent.replaceAll(manage.getCode() + manage.getVersion(), newRule.getCode() + newRule.getVersion());
//	                ruleContent = ruleContent.replaceAll(manage.getCode() + "_" + manage.getVersion(), newRule.getCode() + "_" + newRule.getVersion());
	                ruleContent = ruleContent.replaceAll(manage.getCode(), newRule.getCode());
	                verInfo.setRuleContent(ruleContent);
	                ruleVersioninfoService.save(verInfo);
	            } catch (Exception e) {
	                throw new BizException(e, "");
	            }
            }
        }
    }

    /**
     * 删除规则模型（将状态标志位至0）
     * 删除前检查被引用情况，如被引用，不能删除
     */
    public List<ReferenceModel> delete(String manageIds,String projectCode) throws BizException {
    	if(StringUtils.isEmpty(manageIds))
    		throw new BizException("E-000101");
    	List<ReferenceModel> referenceList = new ArrayList<ReferenceModel>();
    	for(String manageId : manageIds.split(",")) {
    		if(StringUtils.isEmpty(manageId))
    			continue;
            RuleManage manage = this.getById(manageId);
            if (manage == null) {
                throw new BizException("E-100001");
            }
            List<ReferenceModel>  tmpList = ruleFlowRectsService.findListByModelCode(manage.getCode(),projectCode);
            List<RuleReleModel> releModelList= ruleReleModelService.findReleModelListForDel(projectCode, manage.getCode());
            if(tmpList!=null && tmpList.size()>0) {
            	for (ReferenceModel referenceModel : tmpList) {
            		referenceModel.setReferenceName(manage.getName());
				}
            	referenceList.addAll(tmpList);
            }else if(releModelList!=null && releModelList.size()>0){
                for (RuleReleModel ruleReleModel : releModelList){
                    ReferenceModel referenceModel = new ReferenceModel();
                    referenceModel.setReferenceName(manage.getName());
                    referenceModel.setReferenceName(ruleReleModel.getName());
                    referenceModel.setReferenctType(ruleReleModel.getModelType());
                    referenceList.add(referenceModel);
                }
            }
            else {
                manage.setStatus("0");
                if("23".equals(manage.getModelType())||"08".equals(manage.getModelType())) {
	                String name = manage.getCode();
	                RuleDataset ruleDataset = new RuleDataset();
	                ruleDataset.setName(name);
	                ruleDataset.setProjectcode(manage.getProjectCode());
	                List<RuleDataset> list = ruleDatasetDao.findDatasetList(ruleDataset);
	                if(list!=null&&list.size()>0) {
	                	String[] arrs = {"weightList","totalweight","activeList","activegroupList"};
	                    for(RuleDataset rds:list) {
	                    	ruleDatasetDao.deleteflag(rds);
	                    	RuleDataparams ruleDataparams = new RuleDataparams();
	                    	ruleDataparams.setDatasetId(rds.getId());
	                    	ruleDataparams.setClassName(rds.getName());
	                    	for(String paramName:arrs) {
	                    		ruleDataparams.setName(paramName);
	                    		List<RuleDataparams> rdps = ruleDataparamsDao.findList(ruleDataparams);
	                    		if(rdps!=null&&rdps.size()>0) {
		                    		for(RuleDataparams ruledataparams:rdps) {
		                    			ruleDataparamsDao.deleteflag(ruledataparams);
		                    		}
	                    		}
	                    	}
	                    }
	                }
                }
                
                this.saveOrUpdate(manage);
            }
    	}
    	return referenceList;
    }


    @Override
    public void delete(RuleManage entity) {
        super.delete(entity);
        RuleModelAuthority authInfo = new RuleModelAuthority();
        authInfo.setManageId(entity.getId());
        List<RuleModelAuthority> list = this.ruleModelAuthorityService.findList(authInfo);
        if (list != null && list.size() > 0) {
            this.ruleModelAuthorityService.delete(list.get(0));
        }
    }

    @Override
    public List<RuleManageVO> findRuleManageVO(RuleManageVO condition) {
        // TODO Auto-generated method stub
        return this.dao.findRuleManageVO(condition);
    }
    
    
    /**
     * 根据项目编号，规则模型编号查找规则模型
     */
    public RuleManage findByCode(String code, String projectCode) throws BizException {
        if (code == null) {
            return null;
        }
        RuleManage queryManage = new RuleManage();
        queryManage.setCode(code);
        queryManage.setProjectCode(projectCode);
        RuleManage ruleManage = null;
        List<RuleManage> list = this.findList(queryManage);
        if (list == null || list.size() == 0)
            throw new BizException("E-000600");
        ruleManage = list.get(0);
        return ruleManage;
    }
	
	@Override
	public void checkImport(RuleManage cur, String modelType) {
		RuleManage entity = new RuleManage();
		entity.setProjectCode(cur.getProjectCode());
		entity.setModelType(modelType);
		List<RuleManage> findList = this.findList(entity);
		for(RuleManage rm:findList){
			if(rm.getName().equals(cur.getName())){
				cur.setId(rm.getId());
				cur.setIsNewRecord(false);
				return;
			}
		}
		
	}

	/**
	 * 根据ruleMange 获取RuleBaseService
	 * @param ruleManage
	 * @return
	 */
	public RuleBaseService<?> setRuleBaseService(String modelType) {
		if(RuleModelTypeEnum.CodeBlock.getCode().equals(modelType)){
			//代码块
			return ruleCodeblockService;
		}else if(RuleModelTypeEnum.DataComponet.getCode().equals(modelType)){
			//数据挖掘
			return dataComponentService;
		}else if(RuleModelTypeEnum.DataMining.getCode().equals(modelType)){
			//数据挖掘
			return dataMiningService;
		}else if(RuleModelTypeEnum.DecisionTree.getCode().equals(modelType)){
			//决策树
			return decisionTreeService;
		}else if(RuleModelTypeEnum.DecisionTable.getCode().equals(modelType)){
			//决策表
			return decisionTableService;
		}else if(RuleModelTypeEnum.ScoreModel.getCode().equals(modelType)){
			//评分模型
			return scoreModelService;
		}else if(RuleModelTypeEnum.RuleFlow.getCode().equals(modelType)){
			//规则流
			return ruleFlowService;
		}else if(RuleModelTypeEnum.StrategyFlow.getCode().equals(modelType)){
			//规则流
			return ruleFlowService;
		}else if(RuleModelTypeEnum.PolicyRuleGroup.getCode().equals(modelType)){
			//政策规则集
			return ruleGroupService;
		}else if(RuleModelTypeEnum.RuleFunction.getCode().equals(modelType)){
			//规则函数
			return ruleGroupService;
		}else if(RuleModelTypeEnum.GeneralRule.getCode().equals(modelType)){
			//规则
			return ruleGroupService;
		}else if(RuleModelTypeEnum.RuleGroup.getCode().equals(modelType)){
			//规则集
			return ruleGroupService;
		}else if(RuleModelTypeEnum.SingleTblIndex.getCode().equals(modelType)){
			//一维表索引
			return singleTblIndexService;
		}else if(RuleModelTypeEnum.RuleAndGroup.getCode().equals(modelType)){
			//规则和规则集
			return ruleGroupService;
		}
		return ruleBaseService;
	}

	@Override
	@Transactional
	public RuleManage updateActiveVersion(List<String> list) throws BizException {
		List<String> rgIds = new ArrayList<String>();
		RuleManage updateManage = null;
		for (String id : list) {
            updateManage = this.dao.get(id);
            this.checkDrl(updateManage);
			RuleManage ruleManage = new RuleManage();
			RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
			ruleManage.setId(id);
			ruleManage.setActiveVersion(updateManage.getVersion());
            ruleManage.setStatus("2");
            ruleVersioninfo.setVersion(updateManage.getVersion());
			this.dao.updateActiveVersion(ruleManage); //修改有效版本为最新版本,并更改状态
			//将ruleversioninfo里is_valid字段修改
			ruleVersioninfo.setManageId(id);
			ruleVersioninfo.setIsValid("1");
			ruleVersioninfoService.updateIsValid(ruleVersioninfo);
            if(updateManage.getModelType().equals(RuleModelTypeEnum.GeneralRule.code)) {
            	//规则生效，需要保存关联规则集，先收集规则id，关联规则集可能相同，防止重复
            	rgIds.add(id);
            }
			//将审批同意的组件全部解冻
			this.dao.updateRuleModelAuthority(ruleManage);
		}
		if(rgIds.size()>0) {
			ruleGroupService.updateRuleGoupDRL(rgIds,updateManage.getProjectCode());
		}
		return null;
	}
	
	private  void   checkDrl(RuleManage updateManage) {
	
		if (RuleModelTypeEnum.RuleFlow.code.equals(updateManage.getModelType()) || RuleModelTypeEnum.CodeBlock.code.equals(updateManage.getModelType())) {
			return ;
		}
		RuleVersioninfo  queryVersion = new  RuleVersioninfo();
		queryVersion.setManageId(updateManage.getId());
		queryVersion.setVersion(updateManage.getVersion());
		List<RuleVersioninfo> lists =this.ruleVersioninfoService.findList(queryVersion);
		if (lists != null &&lists.size()>0) {
			RuleVersioninfo  tmpVersion =  lists.get(0);
			List<ResourceContentInfo> resList = new  ArrayList<>();
			ResourceContentInfo  res = new  ResourceContentInfo(tmpVersion.getRuleContent(),ResourceType.DRL );
			String  func=this.ruleCodeblockService.getEffectiveFunc(updateManage.getProjectCode());
			if (func != null) {
				resList.add(new ResourceContentInfo(func, ResourceType.DRL));
			}
			resList.add(res);
			try {
				KieBaseFactory.getInstance().checkDrl(resList);
			} catch (Exception e) {
				throw  new  BizException("",e.getMessage());
			}
		}
	}

	@Override
	public List<RuleManage> findMainManageList(RuleManage queryManage) {
		return this.dao.findMainManageList(queryManage);
	}

	@Override
	public List<RuleManage> findListByRefManage(RuleManage ruleManage) {
		return this.dao.findListByRefManage(ruleManage);
	}

	@Override
	public List<RuleManage> findListByIds(List<String> ids) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("ids", ids);
		return this.dao.findListByIds(map);
	}
	
    @Override
	public void clearVersion(RuleManage ruleManage,List<String> versions) {
		String version = ruleManage.getVersion();//当前版本不清理
		String activeVersion = ruleManage.getActiveVersion();//激活版本不清理
		if(StringUtils.isNotEmpty(activeVersion) && versions.contains(activeVersion)) {
			versions.remove(activeVersion);
		}
		if(StringUtils.isNotEmpty(version) && versions.contains(version)) {
			versions.remove(version);
		}
		if(versions!=null&&versions.size()>0) {
			this.ruleVersioninfoService.deleteByMutilVersion(ruleManage,versions);
			
			RuleBaseService<?> ruleBaseService = setRuleBaseService(ruleManage.getModelType());
	        if (ruleBaseService != null) {
	    	   ruleBaseService.clearVersion(ruleManage, versions);
	           this.ruleReferenceDataService.deleteByMutilVersion(ruleManage, versions);
	        } else {
	           throw new BizException("版本清理失败!");
	        }
		}else {
			throw new BizException("E-000300");
		}
	}
    
	private void updateAntoApprove(RuleManage ruleManage) {
		String  isapprove =Global.getConfig("version.isapprove");
		if (!StringUtils.isEmpty(isapprove)) {
			if ("0".equals(isapprove)) {
				if (!"0".equals(ruleManage.getStatus())) {
				   ruleManage.setStatus("2");
				   ruleManage.setActiveVersion(ruleManage.getVersion());
				}
			}
		}
	}

	@Override
	public void save(RuleManage entity) {
		this.updateAntoApprove(entity);
		super.save(entity);
	}
	/**
     * 更新关联层级ID（初始化）
     * @param condition
     * @return
     */
    public int updateRankId(RuleManage condition) {
    	return this.dao.updateRankId(condition);
    }
    /**
     * 根据条件获取数据量
     * @param ruleManage
     * @return
     */
    public int countListFindName(RuleManage ruleManage,String modelType) {
        ruleManage.setModelType(modelType);
        return this.dao.countListFindName(ruleManage);
    }

    /**
     * 根据条件获取数据量
     * @param condition
     * @return
     */
    public int countList(RuleManage condition) {
    	return this.dao.countList(condition);
    }
    
    
   public  RuleVersioninfo  findRuleVersionInfo(String  projectCode,String  manageId) {
    	RuleVersioninfo  queryInfo  = new  RuleVersioninfo();
    	queryInfo.setProjectCode(projectCode);
    	queryInfo.setManageId(manageId);
     	List<RuleVersioninfo> list = this.ruleVersioninfoService.findList(queryInfo);
     	if (list != null &&  list.size()>0) {
     		return  list.get(0);
     	}
     	return  null;
    }

	
}
